package com.example.singing.view;

import com.example.singing.manager.CompetitionManager;
import com.example.singing.manager.ScoreManager;
import com.example.singing.manager.TeamManager;
import com.example.singing.model.Competition;
import com.example.singing.model.Score;
import com.example.singing.model.Team;
import com.example.singing.model.User;
import com.example.singing.util.AlertUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 评分界面
 */
public class ScoringView {
    private VBox view;
    private CompetitionManager competitionManager;
    private TeamManager teamManager;
    private ScoreManager scoreManager;
    private User currentUser;
    private int judgeIndex = -1; // 评委对应的评分索引（-1表示管理员或未分配）

    // 无参构造函数，保留以兼容旧代码
    public ScoringView() {
        this.competitionManager = new CompetitionManager();
        this.teamManager = new TeamManager();
        this.scoreManager = new ScoreManager();
        createView();
    }

    // 带用户参数的构造函数
    public ScoringView(User user) {
        this.currentUser = user;
        this.competitionManager = new CompetitionManager();
        this.teamManager = new TeamManager();
        this.scoreManager = new ScoreManager();
        // 为评委分配固定的评分索引（基于用户名的哈希值）
        if (user != null && "评委".equals(user.getRole())) {
            judgeIndex = Math.abs(user.getUsername().hashCode() % 5); // 分配到0-4中的一个索引
        }
        createView();
    }

    /**
     * 创建评分界面
     */
    private void createView() {
        VBox scoringView = new VBox(20);
        scoringView.setPadding(new Insets(20));

        Label title = new Label("评分管理");
        title.setStyle("-fx-font-size: 20px; -fx-font-weight: bold; -fx-text-fill: #673ab7;");

        // 选择比赛和队伍
        HBox selectionBox = new HBox(15);
        selectionBox.setAlignment(javafx.geometry.Pos.CENTER_LEFT);

        ComboBox<Competition> competitionCombo = new ComboBox<>();
        competitionCombo.setItems(FXCollections.observableArrayList(competitionManager.getAllCompetitions()));
        competitionCombo.setPromptText("选择比赛");
        competitionCombo.setPrefWidth(200);

        ComboBox<Team> teamCombo = new ComboBox<>();
        teamCombo.setPromptText("选择队伍");
        teamCombo.setPrefWidth(200);

        // 先创建评分界面容器，确保在监听器前定义
        VBox scoringBox = new VBox(15);
        scoringBox.setPadding(new Insets(20));
        scoringBox.setStyle("-fx-background-color: white; -fx-background-radius: 10;");
        scoringBox.setVisible(false);

        // 当选择比赛时，更新队伍列表，只显示该比赛的队伍
        competitionCombo.valueProperty().addListener((obs, oldVal, newVal) -> {
            if (newVal != null) {
                // 清空并重新加载队伍列表
                teamCombo.getItems().clear();
                
                // 根据选中的比赛筛选队伍
                List<Team> allTeams = teamManager.getAllTeams();
                System.out.println("所有队伍数量: " + allTeams.size());
                
                List<Team> competitionTeams = allTeams.stream()
                        .filter(team -> {
                            // 验证队伍数据完整性
                            if (team == null || team.getCompetitionId() == null) {
                                System.out.println("跳过无效队伍: " + (team != null ? team.getName() : "null"));
                                return false;
                            }
                            
                            boolean matches = newVal.getId().equals(team.getCompetitionId());
                            System.out.println("检查队伍: " + team.getName() + 
                                             ", 队伍比赛ID: " + team.getCompetitionId() + 
                                             ", 选中比赛ID: " + newVal.getId() + 
                                             ", 是否匹配: " + matches);
                            return matches;
                        })
                        .toList();
                
                System.out.println("找到匹配的队伍数量: " + competitionTeams.size());
                for (Team team : competitionTeams) {
                    System.out.println("匹配的队伍: " + team.getName() + " (ID: " + team.getId() + ")");
                }
                
                if (competitionTeams.isEmpty()) {
                    // 如果没有找到与比赛关联的队伍，则添加提示信息
                    teamCombo.setPromptText("此比赛目前并没有参赛选手 ¯\\_(ツ)_/¯");
                } else {
                    teamCombo.setItems(FXCollections.observableArrayList(competitionTeams));
                    teamCombo.setPromptText("选择队伍");
                }
                
                teamCombo.setValue(null); // 重置队伍选择
            } else {
                teamCombo.getItems().clear();
            }
            // 只有选择了具体的比赛和队伍才显示评分界面
            scoringBox.setVisible(newVal != null && teamCombo.getValue() != null);
        });

        selectionBox.getChildren().addAll(
                new Label("比赛:"), competitionCombo,
                new Label("队伍:"), teamCombo
        );

        // 评分输入
        // scoringBox已经在前面定义了

        Label scoringTitle = new Label("评委评分");
        scoringTitle.setStyle("-fx-font-size: 16px; -fx-font-weight: bold;");

        GridPane scoreGrid = new GridPane();
        scoreGrid.setHgap(10);
        scoreGrid.setVgap(10);

        // 创建5个评委的评分输入框
        Slider[] judgeSliders = new Slider[5];
        Label[] scoreLabels = new Label[5];

        for (int i = 0; i < 5; i++) {
            Label judgeLabel = new Label("评委 " + (i + 1) + ":");
            judgeLabel.setStyle("-fx-font-weight: bold;");

            Slider slider = new Slider(0, 10, 8);
            slider.setShowTickLabels(true);
            slider.setShowTickMarks(true);
            slider.setMajorTickUnit(1);
            slider.setBlockIncrement(0.1);
            slider.setPrefWidth(300);

            Label scoreLabel = new Label("8.0");
            scoreLabel.setStyle("-fx-font-weight: bold; -fx-text-fill: #673ab7;");

            // 绑定滑块值和标签显示
            slider.valueProperty().addListener((obs, oldVal, newVal) -> {
                scoreLabel.setText(String.format("%.1f", newVal.doubleValue()));
            });

            // 根据用户角色设置滑块可编辑状态
            if (currentUser != null) {
                if ("评委".equals(currentUser.getRole())) {
                    // 评委只能编辑自己的评分
                    slider.setDisable(i != judgeIndex);
                    if (i == judgeIndex) {
                        judgeLabel.setText("我的评分:");
                        judgeLabel.setStyle("-fx-font-weight: bold; -fx-text-fill: #4caf50;");
                    } else {
                        judgeLabel.setStyle("-fx-font-weight: bold; -fx-text-fill: #9e9e9e;");
                        scoreLabel.setStyle("-fx-font-weight: bold; -fx-text-fill: #9e9e9e;");
                    }
                }
                // 管理员可以编辑所有评分
            }

            judgeSliders[i] = slider;
            scoreLabels[i] = scoreLabel;

            scoreGrid.add(judgeLabel, 0, i);
            scoreGrid.add(slider, 1, i);
            scoreGrid.add(scoreLabel, 2, i);
        }

        // 最终得分
        Label finalScoreLabel = new Label("最终得分: -");
        finalScoreLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold; -fx-text-fill: #ff9800;");

        Button calculateBtn = new Button("计算得分");
        calculateBtn.setStyle("-fx-background-color: #673ab7; -fx-text-fill: white;");
        calculateBtn.setOnAction(e -> {
            // 计算最终得分（去掉最高分和最低分，取平均）
            double[] scores = new double[5];
            for (int i = 0; i < 5; i++) {
                scores[i] = judgeSliders[i].getValue();
            }

            Arrays.sort(scores);
            double sum = 0;
            for (int i = 1; i < 4; i++) { // 去掉第一个和最后一个
                sum += scores[i];
            }
            double finalScore = sum / 3;

            finalScoreLabel.setText(String.format("最终得分: %.2f", finalScore));
        });

        Button submitBtn = new Button("提交评分");
        submitBtn.setStyle("-fx-background-color: #4caf50; -fx-text-fill: white;");
        submitBtn.setOnAction(e -> {
            if (competitionCombo.getValue() == null || teamCombo.getValue() == null) {
                AlertUtil.showErrorAlert("错误", "请先选择比赛和队伍");
                return;
            }

            // 检查是否已经为该比赛和队伍提交过评分
            String competitionId = competitionCombo.getValue().getId();
            String teamId = teamCombo.getValue().getId();
            List<Score> existingScores = scoreManager.getScoresByCompetitionAndTeam(competitionId, teamId);
            if (!existingScores.isEmpty()) {
                AlertUtil.showErrorAlert("错误", "同一个比赛同一个队伍不能多次评分");
                return;
            }

            // 收集评分
            List<Double> judgeScores = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                judgeScores.add(judgeSliders[i].getValue());
            }

            // 计算最终得分
            double[] scoresArray = new double[5];
            for (int i = 0; i < 5; i++) {
                scoresArray[i] = judgeScores.get(i);
            }
            Arrays.sort(scoresArray);
            double sum = 0;
            for (int i = 1; i < 4; i++) {
                sum += scoresArray[i];
            }
            double finalScore = sum / 3;

            // 创建评分记录
            Score newScore = new Score(
                    "SCORE" + (scoreManager.getAllScores().size() + 1),
                    competitionCombo.getValue().getId(),
                    teamCombo.getValue().getId(),
                    judgeScores,
                    finalScore
            );

            scoreManager.addScore(newScore);
            AlertUtil.showInfoAlert("成功", "评分已提交，最终得分: " + String.format("%.2f", finalScore));

            // 重置界面
            for (Slider slider : judgeSliders) {
                slider.setValue(8);
            }
            finalScoreLabel.setText("最终得分: -");
        });

        HBox buttonBox = new HBox(15);
        buttonBox.setAlignment(javafx.geometry.Pos.CENTER);
        buttonBox.getChildren().addAll(calculateBtn, submitBtn);

        scoringBox.getChildren().addAll(scoringTitle, scoreGrid, finalScoreLabel, buttonBox);

        // 当选择比赛和队伍后显示评分界面
        competitionCombo.valueProperty().addListener((obs, oldVal, newVal) -> {
            scoringBox.setVisible(newVal != null && teamCombo.getValue() != null);
        });

        teamCombo.valueProperty().addListener((obs, oldVal, newVal) -> {
            scoringBox.setVisible(newVal != null && competitionCombo.getValue() != null);
        });

        scoringView.getChildren().addAll(title, selectionBox, scoringBox);
        this.view = scoringView;
    }

    /**
     * 获取界面视图
     */
    public VBox getView() {
        return view;
    }
}